package homework.homework02.entry;


import homework.homework02.domain.Awards;

import java.util.Random;

public class Entry {

    //封装一个随机数对象
    private static Random random = new Random();

    public static void main(String[] args) {

        // 定义奖项数组,并为其设置值
        Awards[] awards = new Awards[4];
        awards[0] = new Awards("一等奖", 1);
        awards[1] = new Awards("二等奖", 2);
        awards[2] = new Awards("三等奖", 3);
        awards[3] = new Awards("谢谢惠顾", 4);

        // 统计各奖项出现次数
        int[] count = new int[4];
        // 补全代码
        for (int i = 0; i < 100; i++) {
            //获取一个随机数
            // 生成[0,10)的随机数
            int randomNum = random.nextInt(10);

            // 使用二分查找确定奖项
            Awards award = binarySearch(awards, randomNum);

            // 统计结果
            switch (award.getName()) {
                case "一等奖":
                    count[0]++;
                    System.out.println("恭喜您获得了一等奖");
                    break;
                case "二等奖":
                    count[1]++;
                    System.out.println("恭喜您获得了二等奖");
                    break;
                case "三等奖":
                    System.out.println("恭喜您获得了三等奖");
                    count[2]++;
                    break;
                case "谢谢惠顾":
                    System.out.println("很遗憾,是谢谢惠顾");
                    count[3]++;
                    break;
            }
        }

        // 输出统计结果
        System.out.println("一等奖出现次数: " + count[0]);
        System.out.println("二等奖出现次数: " + count[1]);
        System.out.println("三等奖出现次数: " + count[2]);
        System.out.println("谢谢惠顾出现次数: " + count[3]);
    }


    // 二分查找实现
    public static Awards binarySearch(Awards[] awards, int num) {
        //对抽奖结果进行判断
       /* if (num >= 1 && num < 3) {
            return awards[1];
        } else if (num >= 3 && num < 6) {
           return awards[2];
        } else if (num >= 6 && num < 10) {
           return awards[3];
        } else {
           return awards[0];
        }*/
        //计算累计权重的范围
        int[] ranges = new int[awards.length + 1];
        ranges[0] = 0;
        for (int i = 1; i <= awards.length; i++) {
            ranges[i] = ranges[i - 1] + awards[i - 1].getWeight();
        }

        //第i个奖项的范围 = [sum(weights[0..i-1]), sum(weights[0..i]))
        //二分查找确定范围
        int left = 0;
        int right = ranges.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (num >= ranges[mid] && num < ranges[mid + 1]) {
                return awards[mid];
            } else if (num < ranges[mid]) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return awards[0]; // 默认返回一等奖（实际不会执行到这里）
    }

}
